package com.itita.weibo.manager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import weibo4andriod.Count;
import weibo4andriod.Paging;
import weibo4andriod.Status;
import weibo4andriod.User;
import weibo4andriod.WeiboException;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.itita.weibo.db.DataBaseOpenHelpler;
import com.itita.weibo.model.Task;
import com.itita.weibo.util.WeiboUtil;

/**
 * 微博管理
 * @author 焦明 2010-5-10 23:35
 *
 */
public final class WeiboManager {
    
	 /**
	  * 
	  * @return
	  */
	 public static  boolean clearCache(Context context){
		boolean isSucc4ClearHomeTableCache = new WeiboDao(context).clearCache();
		boolean isSucc4ClearImageCache = false;
		try {
			//清除缓存图片 	
			clearImageCache();
			isSucc4ClearImageCache = true;
		} catch (Exception e) {
			e.printStackTrace();
		}
	    return true;	 
	 }
	 
	 public User findLoginingUser(Context context){
		 return new WeiboDao(context).findLoginingUser();
	 }
    
	 public final void addUser(Context context, User user){
		 this.addUser(context, user.getUsername(), user.getPassword(), user.getId(), user.isLogin(), user.getName(), user.getAccessToken(), user.getAccessTokenSecret());
	 }
	 /**
	  * 添加用户信息
	  * @param context
	  * @param username
	  * @param password
	  * @param userId
	  * @param isLogin
	  * @param name
	  * @param accessToken
	  * @param accessTokenSecret
	  */
	public final void addUser(Context context, String username, String password, int userId, boolean isLogin, String name, String accessToken, String accessTokenSecret){
		new WeiboDao(context).addUser(username, password, isLogin, userId,name, accessToken, accessTokenSecret);
	}
	
	/**
	 * 删除用户
	 * @param context
	 * @param username
	 * @throws Exception
	 */
	public final void delUser(Context context, String username) throws Exception{
		new WeiboDao(context).delUser(username);
	}
	
	
	 public ArrayList<User> searchUser(Context context){
		 return new WeiboDao(context).searchUser();
	 }
	/**
	 * 保存首页信息
	 * @param statuses
	 * @param context
	 */
	public static final void saveStatusDataToLocalHomeTable (ArrayList<Status> statuses, Context context){
		WeiboDao weiboManager = new WeiboDao(context);
		////System.out.println("-----------saveStatusDataToLocalHomeTable()----------------");
		for (Iterator iterator = statuses.iterator(); iterator.hasNext();) {
			////System.out.println("++++++++++++++++++正在存储数据saveStatusDataToLocalHomeTable++++++++++++++++++");
			Status status = (Status) iterator.next();
		    weiboManager.addHomeTableData(status, MainService.currentUser.getId());
		    ////System.out.println("+++++++++++++++存储完一条微博信息saveStatusDataToLocalHomeTable+++++++++++++++++");
		}
	}
	

	
	/**
	 * 从本地加载微博推荐信息
	 * @param context
	 * @return
	 * @throws WeiboException
	 */
	public static final ArrayList<Status> loadRecommendInfoFromLocal(Context context, int newPage, int pageSize) throws WeiboException{
		int startResult = pageSize * (newPage-1) + 1;
		int maxResult =   (pageSize + 1)*newPage;
		ArrayList<Status> alls = new WeiboDao(context) .searchStatuesFromLocal(
				new StringBuffer().append(DataBaseOpenHelpler.WEIGHT_OF_ODERY_NAME)
				.append(" limit ").append(startResult).append(",").append(maxResult).toString(),
				MainService.currentUser.getId()
				);
		WeiboUtil.processStatuses(alls, Task.TASK_GET_USER_IMAGE_ICON_FOR_RECOMMOND_STATUS, Task.TASK_GET_USER_WEIBO_IMAGE_FOR_RECOMMOND_STATUS);
		
		return alls;
	}
	
	 
	/**
	 * 从网络获取推荐信息  
	 * @param context
	 * @param newPage
	 * @param pageSize
	 * @param baseDataSeize
	 * @return
	 * @throws WeiboException
	 */
	public static final ArrayList<Status> loadRecommendInfoFromNet(Context context, int newPage, int pageSize, int baseDataSeize) throws WeiboException{
		////System.out.println("---------抓取推荐信息开始--------------");
		ArrayList<Status> alls = null;
 	final Paging p = new Paging(newPage, pageSize);// 创建分页对象
		alls = (ArrayList<Status>) MainService.mainService.weibo.getFriendsTimeline(p);
		HashMap<Status, Long> hashMap = new HashMap();              
		try {
			long rtNumu = 0;
			 long commNum = 0;
			 Status status = null;
			 for (Iterator iterator = alls.iterator(); iterator.hasNext();) {
			    status = (Status) iterator.next();
				List<Count> counts =  MainService.mainService.weibo.getCounts(String.valueOf(status.getId()));
				rtNumu = counts.get(0).getRt();
				commNum = counts.get(0).getComments();
				//将status的转发， 评论存注入都status中
				status.setCommNum(commNum);
			    status.setRetweetedNum(rtNumu);
			  //将status的转发， 评论存注入都status中
				hashMap.put(status, WeiboUtil.calStatusWeight(rtNumu, commNum));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map.Entry<Status, Long>> infoIds = new ArrayList<Map.Entry<Status, Long>>(hashMap.entrySet());
		 
	   Collections.sort(infoIds, new Comparator<Map.Entry<Status, Long>>() {   
	     public int compare(Map.Entry<Status, Long> o1, Map.Entry<Status, Long> o2) {      
	        return (int) (o2.getValue() - o1.getValue()); //降序
	     }
	   });
	   
	   ArrayList<Status> recAlls = new ArrayList<Status>();
		//排序后
	   for (int i = 0; i < infoIds.size(); i++) {
		   if(i == 5){
			   break;
		   }
		   Status status = infoIds.get(i).getKey();
		   recAlls.add(status);
	   }
	   WeiboUtil.processStatuses(recAlls, 
			   Task.TASK_GET_USER_IMAGE_ICON_FOR_RECOMMOND_STATUS,
			   Task.TASK_GET_USER_WEIBO_IMAGE_FOR_RECOMMOND_STATUS);
	  ////System.out.println("---------抓取推荐信息结束--------------");
	  return recAlls;
	}
	
    
	/**
	 * 获取更多的推荐信信息	
	 * @param context
	 * @param newPage
	 * @param pageSize
	 * @param baseDataSeize
	 * @return
	 * @throws WeiboException
	 */
	public static final ArrayList<Status> loadRecommendMoreInfoFromNet(Context context, int newPage, int pageSize, int baseDataSeize) throws WeiboException{
		////System.out.println("---------抓取推荐信息开始--------------");
		ArrayList<Status> alls = null;
		final Paging p = new Paging(newPage, pageSize);// 创建分页对象
		alls = (ArrayList<Status>) MainService.mainService.weibo.getFriendsTimeline(p);
		HashMap<Status, Long> hashMap = new HashMap();              
		try {
			long rtNumu = 0;
			long commNum = 0;
			Status status = null;
			for (Iterator iterator = alls.iterator(); iterator.hasNext();) {
				status = (Status) iterator.next();
				List<Count> counts =  MainService.mainService.weibo.getCounts(String.valueOf(status.getId()));
				rtNumu = counts.get(0).getRt();
				commNum = counts.get(0).getComments();
				status.setCommNum(commNum);
				status.setRetweetedNum(rtNumu);
				hashMap.put(status, WeiboUtil.calStatusWeight(rtNumu, commNum));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		List<Map.Entry<Status, Long>> infoIds = new ArrayList<Map.Entry<Status, Long>>(hashMap.entrySet());
		
		Collections.sort(infoIds, new Comparator<Map.Entry<Status, Long>>() {   
			public int compare(Map.Entry<Status, Long> o1, Map.Entry<Status, Long> o2) {      
				return (int) (o2.getValue() - o1.getValue()); //降序
			}
		});
		
		ArrayList<Status> recAlls = new ArrayList<Status>();
		//排序后
		for (int i = 0; i < infoIds.size(); i++) {
			if(i == 5){
				break;
			}
			Status status = infoIds.get(i).getKey();
			recAlls.add(status);
		}
		WeiboUtil.processStatuses(
				 recAlls,
				 Task.TASK_GET_USER_IMAGE_ICON_FOR_RECOMMOND_STATUS,
				 Task.TASK_GET_USER_WEIBO_IMAGE_FOR_RECOMMOND_STATUS);
		
		////System.out.println("---------抓取推荐信息结束--------------");
		return recAlls;
	}
	
	/**
	 * 从本地加载微博列表信息
	 * @param context
	 * @return 从本地加载的微博列表信息
	 * @throws WeiboException
	 */
	public static final ArrayList<Status> loadStatusesInfoFromLocal(Context context) throws WeiboException{
		ArrayList<Status> alls = new WeiboDao(context).searchStatuesFromLocal(DataBaseOpenHelpler.TIME_OF_ODERY_NAME, MainService.currentUser.getId());
		WeiboUtil.processStatuses(
				   alls, 
				   Task.TASK_GET_USER_IMAGE_ICON, 
				   Task.TASK_GET_WEIBO_IMAGE);
		return alls;
	}
		
	/**
	 * 从网络上加载微博列表信息
	 * @param nowpage
	 * @param pagesize
	 * @return 微博列表信息
	 * @throws WeiboException
	 */
	public static final ArrayList<Status> loadStatusesInfoFromNet(int nowpage, int pagesize) throws WeiboException{
		ArrayList<Status> alls = null;
		final Paging p = new Paging(nowpage, pagesize);// 创建分页对象
		alls = (ArrayList<Status>) MainService.mainService.weibo.getFriendsTimeline(p);
//		WeiboUtil.processStatuses(alls);
		WeiboUtil.processStatuses(
				   alls, 
				   Task.TASK_GET_USER_IMAGE_ICON, 
				   Task.TASK_GET_WEIBO_IMAGE);
		return alls;
	}
	
	
   
	/**
	 * 从缓存中读取图片
	 * @param imageId 
	 * @return
	 */
	public static Bitmap getMyBitmap(String imageId){
		
		  String myJpgPath = new StringBuffer().append("/sdcard/itita/weibo/")
		                     .append(imageId).append(".png").toString();

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1; //;//图片缩放比例,即将当前图片的缩放到1/2显示
        Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
        return bm;
	}
	
	/**
	 * 清除用户图片和微波图片缓存
	 */
	public static void clearImageCache() throws Exception{
		  String myJpgPath = new StringBuffer().append("/sdcard/itita/weibo/").toString();
		  File file = new File(myJpgPath);
		  if(file.isDirectory()){
			 File[] files =  file.listFiles();
			 for(File file2 : files){
				 if(file2.getName().endsWith(".png")){
					 ////System.out.println("正在删除缓存文件");
					 file2.delete();
				 }
			 }
		  }
	 }
	
	/**
	 * 存储图片到缓存中
	 * @param bitName
	 * @param mBitmap
	 */
	public static final void saveMyBitmap(String bitName, Bitmap mBitmap) {
		
		File file = new File("/sdcard/itita/weibo");
	    if(!file.exists()){
		    ////System.out.println(file.mkdirs() ? "文件件/sdcard/itita/weibo穿件成功" : "文件件/sdcard/itita/weibo穿件失败");
	    }
		
		File f = new File(new StringBuffer(
				file.getPath()).append("/").append(bitName)
				.append(".png").toString());
		FileOutputStream fOut = null;
		try {
			f.createNewFile();
		} catch (IOException e) {
			 e.printStackTrace();
		}
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	 
}
